<?php

namespace app\admin\controller\general;

use app\common\controller\Backend;
use think\Db;

/**
 * app启动页管理
 *
 * @icon fa fa-circle-o
 */
class StartUp extends Backend
{

    /**
     * StartUp模型对象
     * @var \app\admin\model\StartUp
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\StartUp;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                try {
                    $params['status'] = $this->model::STATUS_DISABLE;

                    $exist = $this->model
                        ->where('status', $this->model::STATUS_ENABLE)
                        ->where('deletetime', $this->model::DELETE_TIME)
                        ->find();
                    if (!$exist) {
                        $params['status'] = $this->model::STATUS_ENABLE;
                    }

                    $this->model->allowField(true)->save($params);

                    Db::commit();
                }catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success();
            }
            $this->error();
        }
        return parent::add();
    }

    public function enable()
    {
        $ids = request()->param('ids');

        Db::startTrans();
        try {
            $this->model
                ->where([
                    'status'=>$this->model::STATUS_ENABLE,
                    'deletetime' => $this->model::DELETE_TIME
                ])
                ->update(['status'=>$this->model::STATUS_DISABLE]);

            $res = $this->model->where('id',$ids)
                ->update([
                    'status' => $this->model::STATUS_ENABLE,
                    'updatetime' => time()
                ]);
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$res) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

}
